/**
 * @fileOverview <p>The eui.Table.Sorter class.</p>
 * @author marlettas
 * @version $Id: TableSorter.js 106 2009-10-01 08:24:37Z embrace.toolkit $
 */

/**
 * Own implementations of {@link eui.Table.Sorter} allwos you to define own 
 * sorting rules for {@link eui.Table.Table} objects.
 * 
 * @class Prototype UI Extension makes the eui.Table sortable by clicking into the head
 * to sort by. 
 *  
 * @author embrace.toolkit
 * @version $Id: TableSorter.js 106 2009-10-01 08:24:37Z embrace.toolkit $
 */
eui.Table.Sorter = Class.create({
	/** @lends eui.Table.Sorter */ 
	/**
	 * Reference to the parent {@link eui.Table.Table} object.
	 * @type eui.Table.Table
	 * @private
	 */
	table: false,
	/**
	 * Called by constructor when creating an instance of {@link eui.TableSorter}.
	 * 
	 * @public
	 * @param eui.TableSorter.Options parametersoptions to create instance.
	 */
	initialize: function(parameters) {
		this.table = parameters.table;
		if(!this.table)
			throw("NullPointerException: Table could not be null");
	},
	/**
	 * <p>Sorts the data of an {@link eui.Table} using the given sorterName 
	 * and sortingDirection.</p>
	 * 
	 * <p><strong>Fires: {@link eui.Table}.table::data:changed</strong></p>
	 *
	 * @param String sorterName fieldName attribute name to sort by.
	 * @param String direction Sorting direction asc=ascending/desc=descending.
	 * @public
	 */
	sort: function(sorterName, direction) {
		var data = this.table.table.select("tr[page]");
		data.sort(function(val1, val2) {
			var sorter1 = val1.select("[fieldName=" + sorterName + "]").first().innerHTML;
			var sorter2 = val2.select("[fieldName=" + sorterName + "]").first().innerHTML;
			
			if(direction == "asc") {
				if(sorter1 > sorter2)
					result = 1;
				else if(sorter1 < sorter2)
					result = -1;
				else
					result = 0;
				
			}else {
				if(sorter1 < sorter2)
					result = 1;
				else if(sorter1 > sorter2)
					result = -1;
				else
					result = 0;
			}
			
			return result;
		});
		
		var tbody = this.table.table.select("tbody").first();
		data.each(function(tableRow) { tbody.insert(tableRow); });

		this.table.table.fire("data:changed");
	}
});

/**
 * @class allowed Options for construction of a {@link eui.TableSorter}
 * @public
 * @author embrace.toolkit
 */
eui.Table.Sorter.Options = Class.create({
	/** @lends eui.Table.Sorter.Options */ 
	/**
	 * reference to the parent {@link eui.Table.Table} object.
	 * @type eui.Table.Table
	 * @public
	 */
	table: false
});